package cn.kgc.jdbc.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author: mosin
 * @version: v2.0  2022/4/20
 * 德鲁伊连接池工具类
 */
public final class DruidUtil {

    private DruidUtil(){}
    private  static DataSource dataSource =null;
    //初始化资源  读取配置文件
    static {
        //可以读取resources目录下的properties配置文件
        //ResourceBundle druid = ResourceBundle.getBundle("druid");
        //String driver = druid.getString("jdbc.driver");
        //System.out.println("driver = " + driver);
        //创建连接池对象
        try {
            Properties properties = new Properties();
            //通过类加载器加载配置文件
            InputStream in = DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(in);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 获取数据库连接池
    public static DataSource getDataSource(){
        return dataSource;
    }

    //获取连接
    public static  Connection getConnection(){
        //通过数据库连接池获取连接
        Connection connection = null;
        try {
            if(dataSource !=null){
                connection= dataSource.getConnection();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return  connection;
    }
    //释放资源的方法
    public  static  void closeAll(ResultSet rs, Statement statement, Connection connection){
        try {
            if(rs!=null){
                rs.close();
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        try {
            if(statement!=null){
                statement.close();
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        try {
            if(connection!=null){
                connection.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Connection connection = DruidUtil.getConnection();
        System.out.println("connection = " + connection);
    }
}
